﻿// Hubs/ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
using System.Threading.Tasks;
using System;
using System.Text;
using Microsoft.Extensions.Configuration;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;

public class ChatHub : Hub
{
    private readonly IConfiguration _configuration;
    private readonly ILoginServer _loginServer;

    public ChatHub(IConfiguration configuration,ILoginServer loginServer)
    {
        _configuration = configuration;
        _loginServer=loginServer;
    }
    public override async Task OnConnectedAsync()
    {
        // 配置JWT参数
        var settings = new JwtSettings
        {
            SecretKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(_configuration["JWT:secret"])), 
            Issuer = _configuration["JWT:issuer"],
            Audience = _configuration["JWT:audience"],
            ExpireMinutes = 60 * 24 * 7
        };
        // 创建工具实例
        var jwtHelper = new JwtHelper(settings);
        // 解析Token
        var context = Context.GetHttpContext();
        string token = Context.GetHttpContext().Request.Query["access_token"];
        if (string.IsNullOrEmpty(token)||!token.StartsWith("Bearer "))
        {
            return;
        }
        token = token.Substring(7);
        // 检查token是否正确
        var parsedUser = jwtHelper.ParseToken<UserPayload>(token);
        if (parsedUser == null)
        {
            return;
        }
        // 检查用户是否登录
        var account = _loginServer.CheckLogin(parsedUser.aid, parsedUser.code);
        if (account == null)
        {
            return;
        }
        // 从认证后的 User 中获取用户标识
        if (account != null)
        {
            UserConnectionService.AddConnection(account.AId, Context.ConnectionId);
        }
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        var userId = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (userId != null)
        {
            UserConnectionService.RemoveConnection(userId, Context.ConnectionId);
        }
        await base.OnDisconnectedAsync(exception);
    }
}